package com.qf.config;

import com.qf.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.Set;

@Service
public class UserDetailServiceImpl implements UserDetailsService {
    @Autowired
    private UserMapper UserMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
            com.qf.entity.User User=UserMapper.selectByUsername(username);
         if(User==null){
             throw new UsernameNotFoundException("用户不存在");
         }
         //模拟的权限
        //只做认证
        //List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList("add,update,delete");
         //
        Set<String> authset=UserMapper.selectAuthById(User.getId());
         //set返回泛型必须是GrantedAuthority
        Set<GrantedAuthority> auths=new HashSet<>();
        authset.forEach(auth->{
            auths.add(new SimpleGrantedAuthority(auth));
        });
        //加入角色,为了区分必须在前面加入ROLE_
        auths.add(new SimpleGrantedAuthority("ROLE_超级管理员"));
         //返回三个参数
         return new User(User.getUsername(),User.getPassword(),auths);
    }
}
